package com.sky.controller.user;

import cn.hutool.core.util.ObjectUtil;
import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

import static com.sky.constant.BusinessConstant.DISH;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    @ApiOperation("根据分类id查询菜品")
    public Result<List<DishVO>> list(Long categoryId) throws InterruptedException {
        log.info("根据分类ID查询菜品：{}",categoryId);

        //1、从缓存中命中数据，如果命中，直接返回前端
        List<DishVO> dishes = (List<DishVO>)redisTemplate.opsForValue().get(DISH + categoryId); //DISH_1 :  {}
        if(ObjectUtil.isNotEmpty(dishes)){
            return Result.success(dishes);
        }

        //2、如果未命中，查询数据库
        Thread.sleep(2000L);
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

        dishes = this.dishService.list(dish);

        //3、向缓存中存入数据
        redisTemplate.opsForValue().set(DISH + categoryId, dishes);
        return Result.success(dishes);
    }

}
